import axios from 'axios'
import {ElMessage} from "element-plus";
import router from "../../router";

//请求路径
const baseURL = 'http://localhost:8018/'

//创建axios实例
const service = axios.create({
    // 设置基础地址和超时时间
    baseURL,
    // 10秒
    timeout: 10000
})

//请求拦截器 添加请求头
service.interceptors.request.use((config) => {
    // const userStore = useUserStore() // 用户信息store
    const token: string = localStorage.getItem('AccessToken') || ''
    if (token) {
       config.headers['AccessToken'] = token
    }
    return config
})

//响应拦截
service.interceptors.response.use((res) => {
    const originalRequest = res.config;
    // 特殊错误情况401 501错误
    const code = res.data?.code
    if (code === 401) {
        // 发送续期请求续期令牌
        return axios.post('http://localhost:8018/jwt/refreshToken',null,
            {headers: {RefreshToken: localStorage.getItem("RefreshToken")}})
            .then(response=> {
                if (response.data.code == 501) {
                    ElMessage.error(response.data.message)
                    localStorage.removeItem("RefreshToken")
                    localStorage.removeItem("AccessToken")
                    router.push('/login')
                }
            // 更新本地存储的令牌
            localStorage.setItem("AccessToken", response.data.data.AccessToken)
            // 重新发送原始请求
            originalRequest.headers['AccessToken'] = response.data.data.AccessToken
            return axios(originalRequest);
        });
    }
    return res.data
}, (error) => {
    let { message } = error;
    if (message == "Network Error") {
        message = "后端接口连接异常";
    } else if (message.includes("timeout")) {
        message = "系统接口请求超时";
    } else if (message.includes("Request failed with status code")) {
        message = "系统接口" + message.substr(message.length - 3) + "异常";
    }
    ElMessage.error(message);
})

// 返回实例
export default service
